import {
  asyncRoutes,
  constantRoutes
} from '@/router'
import {
  xhrGetMenus
} from '@api/system'
/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(asyncRoutes, routes) {
  const res = []
  asyncRoutes.forEach(a_route => {
    let flag = false
    routes.forEach(route => {
      const tmp = {
        ...route
      }
      if (a_route.path === tmp.path) {
        flag = true
        if (tmp.children) {
          a_route.children = filterAsyncRoutes(a_route.children, tmp.children)
        }
      }
    })
    if (flag) {
      res.push(a_route)
    }
  })
  return res
}

function generationMenus(asyncRoutes, menus) {
  menus.forEach(menu => {
    asyncRoutes.forEach(route => {
      if (route.path === menu.path && route.hidden) {
        menu.hidden = route.hidden
      }
      if (menu.children) {
        generationMenus(route.children, menu.children)
      }
    })
  })
  return menus
}

function loadAutoPage(asyncRoutes, menus) {
  menus.forEach(route => {
    const tmp = {
      ...route
    }
    if (tmp.autoRoute === 1) {
      asyncRoutes.push({
        path: tmp.path,
        name: tmp.path,
        component: () => import('@/views/auto-page'),
        meta: {
          title: tmp.name,
          pageId: tmp.pageId,
          pageData: {}
        }
      })
    }

    asyncRoutes.forEach(a_route => {
      if (a_route.path === tmp.path) {
        if (tmp.children) {
          loadAutoPage(a_route.children, tmp.children)
        }
      }
    })
  })
}

const state = {
  routes: [],
  menus: [],
  permissionMenus: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.routes = constantRoutes.concat(routes)
  },
  SET_MENUS: (state, menus) => {
    state.menus = menus
  },
  SET_PERMISSION_MENUS: (state, permit_menus) => {
    state.permissionMenus = permit_menus
  }
}

const actions = {
  getPermissionMemus({
    commit
  }) {
    return new Promise((resolve, reject) => {
      xhrGetMenus().then(resp => {
        if (resp.data && resp.data.items) {
          commit('SET_MENUS', resp.data.items)
          resolve(resp.data.items)
        }
      }).catch(err => {
        reject(err)
      })
    })
  },
  generateRoutes({
    commit,
    state
  }) {
    return new Promise(resolve => {
      loadAutoPage(asyncRoutes, state.menus)
      const accessedRoutes = filterAsyncRoutes(asyncRoutes, state.menus) || []
      const permit_menus = generationMenus(asyncRoutes, state.menus)
      commit('SET_ROUTES', accessedRoutes)
      commit('SET_PERMISSION_MENUS', permit_menus)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
